package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.RoadLineDto;
import com.hualude.roadsign.dto.LineFaultDto;
import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.FaultCountDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

import static com.hualude.roadsign.service.impl.CountServiceImpl.convertParams;

/**
 * Created by syk on 2017/11/20.
 */
public class RoadLineFaultCountRepositoryImpl {

    @PersistenceContext
    private EntityManager em;

    public List<LineFaultDto> getFault4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select f.RoadLineFaultId,f.RoadLineId,f.RoadLineFaultPhoto,p.RoadLinePhoto,f.RoadLineFaultLevel,f.RoadLineCheck,f.RoadLineMainCheck,\n" +
                "f.RoadLineFaultTime,f.RoadLineCheckTime,o.OrgName AS roadLineOrgName,o2.orgName as roadLineMainOrgName,p.RoadLinePeriod," +
                " p.RoadLineStartRoad,p.RoadLineEndRoad,p.RoadLineRoadName,p.RoadLineServiceLife,p.RoadLineType,p.RoadLineGraphic,\n" +
                "p.RoadLineArea,p.RoadLineCity,p.RoadLineProvince,u.UserName AS roadLineFaultCreatorName, p.roadLineMileage\n" +
                "from tb_line_fault f,tb_org o,tb_org o2,tb_road_line p,tb_user u\n" +
                "where f.RoadLineOrgId = o.OrgId and p.RoadLineMainOrgId=o2.orgId and f.RoadLineId = p.RoadLineId  AND\n" +
                "f.RoadLineFaultCreatorId = u.UserId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.RoadLineFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.RoadLineOrgId IN (" + orgIds + ") or " +
                    "f.RoadLineMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY f.RoadLineFaultTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(LineFaultDto.class));
        List<LineFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getFaultCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_line_fault f,tb_org o WHERE f.RoadLineOrgId= o.OrgId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.RoadLineFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.RoadLineOrgId IN (" + orgIds + ") or " +
                    "f.RoadLineMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<LineFaultDto> getDevice4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select m.RoadLineFaultId,m.RoadLineFaultPhoto,m.RoadLineMaintenancePhoto,m.RoadLineMaintenanceStatus,m.RoadLineMaintenanceTime,RoadLineMoney,\n" +
                "o.OrgName AS roadLineOrgName,m.RoadLineId,s.RoadLineEndRoad,s.RoadLineStartRoad,s.RoadLineArea,s.RoadLineRoadName,s.RoadLineServiceLife,s.RoadLineType,s.RoadLineGraphic,\n" +
                "s.RoadLineCity,s.RoadLineProvince,o2.orgName as roadLineMainOrgName,s.RoadLinePhoto,s.RoadLinePeriod,u.UserName AS roadLineFaultCreatorName,s.roadLineMileage\n" +
                "from tb_line_fault m,tb_user u,tb_org o,tb_org o2,tb_road_line s \n" +
                "where m.RoadLineMaintenanceStatus=2 and m.RoadLineMaintainerId = u.userId and s.RoadLineMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.RoadLineId = s.RoadLineId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.RoadLineMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY m.RoadLineMaintenanceTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(LineFaultDto.class));
        List<LineFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getDeviceCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select count(*) from tb_line_fault m,tb_user u,tb_org o,tb_org o2,tb_road_line s \n" +
                "where m.RoadLineMaintenanceStatus=2 and m.RoadLineMaintainerId = u.userId and s.RoadLineMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.RoadLineId = s.RoadLineId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.RoadLineMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public Integer getRoadLineCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_road_line where RoadLineId like '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and RoadLineProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and RoadLineCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and RoadLineArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and RoadLineRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (RoadLineStartRoad ='" + sQuery[4] + "' or RoadLineEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (RoadLineEndRoad ='" + sQuery[5] + "' or RoadLineStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((RoadLineStartRoad ='" + sQuery[4] + "' and RoadLineEndRoad ='" + sQuery[5] + "') or" +
                    "(RoadLineStartRoad = '" + sQuery[5] + "' and RoadLineEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and RoadLineMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and RoadLineOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (RoadLineOrgId IN (" + orgIds + ") or " +
                    "RoadLineMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<RoadLineDto> getRoadLine4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select c.RoadLineId,c.RoadLinePhoto,c.RoadLineProvince,c.RoadLineCity,c.RoadLineArea," +
                "c.RoadLineRoadName,e.OrgName as roadLineMainOrgName,o.OrgName as roadLineOrgName," +
                "c.roadLineType,c.roadLineGraphic,c.RoadLineInstallTime,c.RoadLineStartRoad," +
                "c.RoadLineEndRoad,c.RoadLineIsComplete from tb_road_line c " +
                "LEFT JOIN tb_org e ON c.RoadLineMainOrgId = e.OrgId " +
                "LEFT JOIN tb_org o ON c.RoadLineOrgId = o.OrgId " +
                "where c.RoadLineId LIKE '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and RoadLineProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and RoadLineCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and RoadLineArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and RoadLineRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (RoadLineStartRoad ='" + sQuery[4] + "' or RoadLineEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (RoadLineEndRoad ='" + sQuery[5] + "' or RoadLineStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((RoadLineStartRoad ='" + sQuery[4] + "' and RoadLineEndRoad ='" + sQuery[5] + "') or" +
                    "(RoadLineStartRoad = '" + sQuery[5] + "' and RoadLineEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and RoadLineMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and RoadLineOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (RoadLineOrgId IN (" + orgIds + ") or " +
                    "RoadLineMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY c.RoadLineInstallTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(RoadLineDto.class));
        List<RoadLineDto> monitorDtos = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return monitorDtos;
    }

    public List<String> getProvinceName(String orgIds) throws Exception {
        String hql = "select distinct c.RoadLineProvince from tb_road_line c where c.RoadLineOrgId in (" + orgIds + ") or " +
                "c.RoadLineMainOrgId in (" + orgIds + ")";
        hql += " order by convert(c.RoadLineProvince using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> province = query.getResultList();
        return province;
    }

    public List<String> getCityName(String orgIds, String provinceName) throws Exception {
        String hql = "select distinct c.RoadLineCity from tb_road_line c where (c.RoadLineOrgId in (" + orgIds + ") or " +
                "c.RoadLineMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.RoadLineProvince = '" + provinceName + "'";
        }
        hql += " order by convert(c.RoadLineCity using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> city = query.getResultList();
        return city;
    }

    public List<String> getAllAreaName(String orgIds, String provinceName, String cityName) throws Exception {
        String hql = "select distinct c.RoadLineArea from tb_road_line c where (c.RoadLineOrgId IN (" + orgIds + ")" +
                " or c.RoadLineMainOrgId IN (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.RoadLineProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.RoadLineCity ='" + cityName + "'";
        }
        hql += " order by convert(c.RoadLineArea using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> area = query.getResultList();
        return area;
    }

    public List<String> getRoadNames(String provinceName, String cityName, String areaName, String orgId, Integer actor) throws Exception {
        String hql = "select distinct c.RoadLineRoadName from tb_road_line c where (c.RoadLineOrgId in (" + orgId + ") or " +
                "c.RoadLineMainOrgId in (" + orgId + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.RoadLineProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.RoadLineCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.RoadLineArea = '" + areaName + "'";
        }
        hql += " order by convert(c.RoadLineRoadName using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getStartRoadName(String orgIds, String provinceName, String cityName, String areaName,
                                         String endRoadName, String roadName) throws Exception {
        String hql = "select distinct c.RoadLineStartRoad from tb_road_line c where (c.RoadLineOrgId in (" + orgIds + ") or " +
                "c.RoadLineMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.RoadLineProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.RoadLineCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.RoadLineArea = '" + areaName + "'";
        }
        if (!endRoadName.equals("-1")) {
            hql += " and c.RoadLineEndRoad = '" + endRoadName + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.RoadLineRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.RoadLineStartRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getEndRoadName(String orgIds, String startRoad, String provinceName, String cityName,
                                       String areaName, String roadName) throws Exception {
        String hql = "select distinct c.RoadLineEndRoad from tb_road_line c where (c.RoadLineOrgId in (" + orgIds + ") or " +
                "c.RoadLineMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.RoadLineProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.RoadLineCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.RoadLineArea = '" + areaName + "'";
        }
        if (!startRoad.equals("-1")) {
            hql += " and c.RoadLineStartRoad = '" + startRoad + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.RoadLineRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.RoadLineEndRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<Integer> getRoadLineTypeCounts(String orgIds, String time, String province, String city, String area, String road) throws Exception {
        String[] timeLimit = {"", ""};
        timeLimit = time.split(" - ");
        String hql = "select c.RoadLineType from tb_road_line c  where (c.RoadLineOrgId in (" + orgIds + ") or " +
                "c.RoadLineMainOrgId in (" + orgIds + ")) AND (c.RoadLineInstallTime between '" + timeLimit[0] + "' and '" + timeLimit[1] + "') " +
                " and c.RoadLineProvince like '%" + province + "%' and c.RoadLineCity like '%" + city + "%' " +
                " and c.RoadLineArea like '%" + area + "%' and c.RoadLineRoadName like '%" + road + "%'   ORDER BY c.RoadLineType";
        Query query = em.createNativeQuery(hql);
        List<Integer> counts = query.getResultList();
        return counts;
    }
}
